//
//  HistoryController.m
//  QRBuildScan
//
//  Created by  on 12-1-2.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//
#import <QuartzCore/QuartzCore.h>
#import "HistoryController.h"
#import "HistoryWabController.h"
#import "MainTabbarController.h"
#import "DetailsContorller.h"
#import "QRImageController.h"
#import "QRnformationController.h"
#import "AppDelegate.h"
#import "QRCodeData.h"

@implementation HistoryController

-(id)init {
    if ((self =[super init])) {
        self.delegate =self;

        p_HistoryRootController = [[UIViewController alloc] init];
        [self pushViewController:p_HistoryRootController animated:NO];
        UIImageView* tCBarBg = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"navbg.png"]];
        tCBarBg.frame =CGRectMake(0, 0, ScreenWidth, 48);
        [self.navigationBar addSubview:tCBarBg];
        [tCBarBg release];
        
        h_title = [[UILabel alloc] initWithFrame:CGRectMake(110, 0, 120, 40)];
        [h_title setBackgroundColor:[UIColor clearColor]];
        h_title.font = [UIFont boldSystemFontOfSize:22];
        h_title.textColor = [UIColor whiteColor];
        h_title.text = @"历史记录";
        [self.navigationBar addSubview:h_title];
        
        r_rightbuttn= [UIButton buttonWithType:UIButtonTypeCustom];
        r_rightbuttn.frame = CGRectMake(250,7, 60, 30);
        [r_rightbuttn setBackgroundImage:[UIImage imageNamed:@"bianji.png"] forState:UIControlStateNormal];
        [r_rightbuttn addTarget:self action:@selector(changrightbuttn) forControlEvents:UIControlEventTouchUpInside];
        [self.navigationBar addSubview:r_rightbuttn];
        [r_rightbuttn retain];
        h_date = [[NSMutableArray alloc] init];

        [self Fetchdata];
    }  
    return self;
}
-(void)viewDidLoad
{
    [p_HistoryRootController.view setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"background.png"]]];
    h_Search = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 2, p_HistoryRootController.view.frame.size.width, 40)];
    h_Search.barStyle = UIBarStyleBlack;
    h_Search.delegate = self;
//    [h_Search setBorderStyle:UITextBorderStyleNone];
//    [h_Search setPlaceholder:@"请输入您的名字"];
//    [h_Search setReturnKeyType:UIReturnKeyDone];
    h_Search.keyboardType = UIKeyboardTypeNamePhonePad;
    
    [p_HistoryRootController.view addSubview:h_Search];
    h_Table = [[UITableView alloc] initWithFrame:CGRectMake(0, 42,p_HistoryRootController.view.frame.size.width ,p_HistoryRootController.view.frame.size.height -42-90 ) style:UITableViewStylePlain];
    [h_Table setDelegate:self];
    [h_Table setDataSource:self];
    [p_HistoryRootController.view addSubview:h_Table];
    h_date = [[NSMutableArray alloc] init];
    [self Fetchdata];
}
-(void)changrightbuttn
{
    if (h_Table.editing) {
        h_Table.editing = NO;
    }
    else{
        h_Table.editing = YES;
    }

}
-(void)Fetchdata
{
    AppDelegate* tDelegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
    NSFetchRequest* tfectreq = [[NSFetchRequest alloc] init];
    NSEntityDescription* tentity =[NSEntityDescription entityForName:@"QRCodeData" inManagedObjectContext:tDelegate.managedObjectContext];
    [tfectreq setEntity:tentity];
    NSArray* objects =[tDelegate.managedObjectContext executeFetchRequest:tfectreq error:nil];
    h_yuandate = [NSMutableArray arrayWithArray:objects];
    [h_yuandate retain];
    [tfectreq release];
    
    NSLog(@"count == %d",[objects count]);
    [self groupdata:objects];
}
-(void)groupdata:(NSArray*)date
{
    if (date!=nil&&[date count]>0) {
        [h_date removeAllObjects];
        BOOL tIsAdd = NO;
        for (QRCodeData* tCodeData in date) {
            tIsAdd = NO;
            for (NSMutableArray* tSectionArr in h_date) {
                QRCodeData* tEnumCode = [tSectionArr lastObject];
                if ([tCodeData.grouptime isEqualToString:tEnumCode.grouptime]) {
                    [tSectionArr addObject:tCodeData];
                    tIsAdd =YES;
                    break;
                }
            }
            if (!tIsAdd) {
                NSMutableArray* tCreateSection = [[[NSMutableArray alloc] init] autorelease];
                [tCreateSection addObject:tCodeData];
                [h_date addObject:tCreateSection];
            }
        }
    }
    NSLog(@"h_date =%d",[h_date count]);
    
    [h_Table reloadData];
    
}
-(void)groupdatas:(NSArray*)date key:(NSString*)keys
{
    if (date!=nil&&[date count]>0) {
        [h_date removeAllObjects];
        BOOL tIsAdd = NO;
        for (QRCodeData* tCodeData in date) {
            tIsAdd = NO;
            if (keys!=nil) {
                if ([tCodeData.content rangeOfString:keys].location==NSNotFound) {
                    continue;
                }
            }
            for (NSMutableArray* tSectionArr in h_date) {
                QRCodeData* tEnumCode = [tSectionArr lastObject];
                if ([tCodeData.grouptime isEqualToString:tEnumCode.grouptime]) {
                    [tSectionArr addObject:tCodeData];
                    tIsAdd =YES;
                    break;
                }
            }
            if (!tIsAdd) {
                NSMutableArray* tCreateSection = [[[NSMutableArray alloc] init] autorelease];
                [tCreateSection addObject:tCodeData];
                [h_date addObject:tCreateSection];
            }
        }
    }
    NSLog(@"h_date =%d",[h_date count]);
}
#pragma mark UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return [h_date count];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSUInteger num = 0;
    if (h_date !=nil&&[h_date count]>0) {
        NSMutableArray* dmun = (NSMutableArray*)[h_date objectAtIndex:section];
        num = [dmun count];
    }

    return num;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView* InSection = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, 320,40)] autorelease];
    [InSection setBackgroundColor:[UIColor grayColor]];
    UILabel* day = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, 300, 20)];
    [day setBackgroundColor:[UIColor clearColor]];
    day.font = [UIFont systemFontOfSize:16];
    day.textColor = [UIColor whiteColor];   
    [InSection addSubview:day];
    [day release];
    if (h_date !=nil&&[h_date count]>0) {
        NSMutableArray* dmun = (NSMutableArray*)[h_date objectAtIndex:section];
        QRCodeData* codedata = (QRCodeData*)[dmun objectAtIndex:0];
        day.text = codedata.grouptime;
    }
    return InSection;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UIView* tview = [[[UIView alloc] initWithFrame:tableView.frame] autorelease];
	[tview setBackgroundColor:[UIColor clearColor]];
	[tableView setBackgroundView:tview];
    static NSString *CellIdentifier = @"Cell";
    NSUInteger row = [indexPath row];
    NSUInteger section = [indexPath section];
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
        cell.selectionStyle =UITableViewCellSelectionStyleBlue;
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        UILabel* tip1 = [[UILabel alloc] initWithFrame:CGRectMake(70, 15, 200, 20)];
        tip1.tag = 1;
        [tip1 setBackgroundColor:[UIColor clearColor]];
        tip1.font = [UIFont systemFontOfSize:18];
        tip1.textColor = [UIColor blackColor];
        [cell.contentView addSubview:tip1];
        
        UILabel* tip2 = [[UILabel alloc] initWithFrame:CGRectMake(70, 40, 200, 20)];
        tip2.tag = 2;
        [tip2 setBackgroundColor:[UIColor clearColor]];
        tip2.font = [UIFont systemFontOfSize:18];
        tip2.textColor = [UIColor blackColor];
        [cell.contentView addSubview:tip2];
        
        UIImageView* imageViews = [[UIImageView alloc] initWithFrame:CGRectMake(10, 13, 45, 54)];
        imageViews.tag = 3;
        [imageViews setImage:[UIImage imageNamed:@"tu1.png"]];
        [cell.contentView addSubview:imageViews];

    }
    if (h_date !=nil&&[h_date count]>0) {
        NSMutableArray* dmun = (NSMutableArray*)[h_date objectAtIndex:section];
        QRCodeData* codedata = (QRCodeData*)[dmun objectAtIndex:row];
        UILabel* ilabel = (UILabel*)[cell.contentView viewWithTag:1];
        ilabel.text = codedata.qrtypename;
        UILabel* ilabel1 = (UILabel*)[cell.contentView viewWithTag:2];
        ilabel1.text = codedata.content;
         UIImageView* iimage = (UIImageView*)[cell.contentView viewWithTag:3];
        NSURL* url = [NSURL URLWithString:codedata.content];
        if (url) {
               [iimage setImage:[UIImage imageNamed:@"tu1.png"]];
        }
        else
        {
               [iimage setImage:[UIImage imageNamed:@"tu2.png"]];
        }
    }
    return cell;
}

#pragma mark UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 80;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (r_rightbuttn.superview) {
        [r_rightbuttn removeFromSuperview];
    }
    NSUInteger row = [indexPath row];
    NSUInteger section = [indexPath section];
    if (h_date !=nil&&[h_date count]>0) {
        NSMutableArray* dmun = (NSMutableArray*)[h_date objectAtIndex:section];
        QRCodeData* codedata = (QRCodeData*)[dmun objectAtIndex:row];
        NSURL* url = [NSURL URLWithString:codedata.content];
        if (url) {
                HistoryWabController* HistoryWab = [[HistoryWabController alloc] init];
                HistoryWab.hw_QRCodeData = codedata;
                [MainTabbarController setTabbarState:YES];
                HistoryWab.hidesBottomBarWhenPushed= YES;
                [self pushViewController:HistoryWab animated:YES];
                [HistoryWab release];
            
        }
        else
        {
            MFMessageComposeViewController*   s_message  = [[MFMessageComposeViewController alloc] init];
            s_message.navigationBar.tintColor= [UIColor blackColor];
            s_message.messageComposeDelegate = self;
            [p_HistoryRootController presentModalViewController:s_message animated:YES];
            [s_message release];
        }
    }



}
#pragma -
#pragma UINavigationControllerDelegate
- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated{
     
    if ([viewController isEqual:p_HistoryRootController]) {
         [self Fetchdata];
        h_title.text = @"历史记录";
        h_title.frame = CGRectMake(110, 0, 120, 40);
        if (!r_rightbuttn.superview) {
            [navigationController.navigationBar addSubview:r_rightbuttn];
        }
    }
    else if([viewController isKindOfClass:HistoryWabController.class])
    {
        HistoryWabController* HistoryWab = (HistoryWabController*)viewController;
        h_title.text = @"网站网址";
        h_title.frame = CGRectMake(120, 0, 120, 40);
        if (!HistoryWab.hw_rightbuttn.superview) {
            [navigationController.navigationBar addSubview:HistoryWab.hw_rightbuttn];
        }
        if (!HistoryWab.hw_leftbuttn.superview) {
            [navigationController.navigationBar addSubview:HistoryWab.hw_leftbuttn];
        }
    }
    else if([viewController isKindOfClass:DetailsContorller.class])
    {
        DetailsContorller* Details = (DetailsContorller*)viewController;
        h_title.text = @"详 情";
        h_title.frame = CGRectMake(130, 0, 120, 40);
        if (!Details.D_leftbuttn.superview) {
            [navigationController.navigationBar addSubview:Details.D_leftbuttn];
        }
    }
    else if([viewController isKindOfClass:QRImageController.class])
    {
        QRImageController* QRImage = (QRImageController*)viewController;
        h_title.text = @"QR码";
        h_title.frame = CGRectMake(130, 0, 120, 40);
        if (!QRImage.qi_leftbuttn.superview) {
            [navigationController.navigationBar addSubview:QRImage.qi_leftbuttn];
        }
    }
    else if([viewController isKindOfClass:QRnformationController.class])
    {
        QRnformationController* QRnformation = (QRnformationController*)viewController;
        h_title.text = @"";
        h_title.frame = CGRectMake(130, 0, 120, 40);
        if (!QRnformation.qf_leftbuttn.superview) {
            [navigationController.navigationBar addSubview:QRnformation.qf_leftbuttn];
        }
    }
}

- (void)navigationController:(UINavigationController *)navigationController didShowViewController:(UIViewController *)viewController animated:(BOOL)animated{
    
    if ([viewController isEqual:p_HistoryRootController]) {
        [self Fetchdata];
    }
    
}
- (BOOL)navigationBar:(UINavigationBar *)navigationBar shouldPushItem:(UINavigationItem *)item{
    return NO;
}

#pragma -
#pragma UINavigationControllerDelegate

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    NSLog(@"%@",searchBar.text);
    [searchBar resignFirstResponder];
    if (searchBar.text!=@"") {
        [self groupdatas:h_yuandate key:searchBar.text];
        [h_Table reloadData];
    }
}
#pragma -
#pragma MFMessageComposeViewControllerDelegate
- (void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult)result
{
    if (result ==  MessageComposeResultCancelled) {
         [controller dismissModalViewControllerAnimated:YES];
    }
    else if(result == MessageComposeResultFailed)
    {
        [controller dismissModalViewControllerAnimated:YES];
    }
    else
    {
        UIAlertView* alertview = [[UIAlertView alloc] initWithTitle:@"提示" message:@"发送短信失败" 
                                                           delegate:nil 
                                                      cancelButtonTitle:@"ok" otherButtonTitles:nil];
        [alertview show];
        [alertview release];

    }
}
-(void) dealloc{
    [p_HistoryRootController release];
    [h_Search release];
    [h_Table release];
    [h_date release];
    [h_yuandate release];
    [h_title release];
    r_rightbuttn = nil;
    [super dealloc];
}

@end
